import { Component } from "@tarojs/taro";
import { View, Text, Picker } from "@tarojs/components";
import { AtButton, AtInput, AtList, AtListItem, AtImagePicker, AtIcon } from "taro-ui";
import { $Req, fileRequest } from "@utils";
import "./index.scss";
import "@components/ShowBox.scss";

export default class Index extends Component {
  config = {
    navigationBarTitleText: "退款",
  };

  constructor() {
    super(...arguments);
    this.state = {
      currentTab: 0,
      address: "",
      switch: false,
      orderDetails: {},
      expressNo: '',
      expressType: '',
      type: null,
      selector: ['收到商品破损', '商品错发、漏发', '收到商品与描述不符', '多拍/拍错/不想要'],
      selectorChecked: '多拍/拍错/不想要',
      files: [],
      uploadUrl:[]
    };
  }

  componentDidShow() {
    let orderDetails = JSON.parse(this.$router.params.orderDetails)
    console.log(orderDetails);
    let type = JSON.parse(this.$router.params.type)
    this.setState({
      type,
      orderDetails
    },() => {
      this.getStoreAddress();
    })

    if (orderDetails.returnDes) {
      this.setState({
        selectorChecked: orderDetails.returnDes
      })
    }

    if (orderDetails.returnDes) {
      this.setState({
        selectorChecked: orderDetails.returnDes
      })
    }

    if (orderDetails.returnImg) {
      let arr = [];
      let as = orderDetails.returnImg.split(',');
      as.forEach(el => {
        arr.push({
          url: el
        })
      })
      this.setState({
        files: arr
      })
    }


    if (orderDetails.refundDes) {
      this.setState({
        selectorChecked: orderDetails.refundDes
      })
    }

    if (orderDetails.refundImg) {
      let arr = [];
      let as = orderDetails.refundImg.split(',');
      as.forEach(el => {
        arr.push({
          url: el
        })
      })
      this.setState({
        files: arr
      })
    }
  }

  async uploadImg(imgUrl) {
    let { code, message, data } = await fileRequest({
      type: "post",
      url: "/file/uploadFile",
      data: imgUrl,
    });
    data = JSON.parse(data);
    if (data.code == 200) {
      /*Taro.showToast({
        title: data.message
      })*/
      this.state.uploadUrl.push(data.data)
      this.setState({
        uploadUrl: this.state.uploadUrl
      })
    } else {
      Taro.showToast({
        title: data.message,
        icon: "none"
      })
    }

  }

  onChanges (files, operationType,delIdx) {
    console.log(files, operationType,delIdx);
    if (operationType == 'remove') {
      let {files, uploadUrl } = this.state;
      files.splice(delIdx, 1);
      uploadUrl.splice(delIdx, 1);
      this.setState({
        files,
        uploadUrl
      })
      return false;
    }
    
    this.uploadImg(files[0].url, 1);
    this.setState({
      files
    })
  }
  onFail (mes) {
    console.log(mes)
  }
  onImageClick (index, file) {
    console.log(index, file)
  }

  onChange = e => {
    this.setState({
      selectorChecked: this.state.selector[e.detail.value]
    })
  }
  onTimeChange = e => {
      this.setState({
        timeSel: e.detail.value
      })
    }
    onDateChange = e => {
      this.setState({
        dateSel: e.detail.value
      })
    }

  // 退款申请
  async callBackMoney() {
    let { data } = await $Req({
      type: "GET",
      url: "/order/orderRefund",
      data: {
        ordersNo: this.state.orderDetails.ordersNo,
        refundDes: this.state.selectorChecked,
        refundImg: this.state.uploadUrl.join(",")
      },
    });
    if (!data) return;

    Taro.showToast({
      title: "退款申请成功, 请等待审批!",
      icon: "none"
    })

    this.state.orderDetails.ordersState = "20005"

    this.setState({
      orderDetails: this.state.orderDetails
    })

  }

  // 退货
  async callBackH() {
    let { expressNo, expressType } = this.state;

    if (expressNo && expressType) {
      let { data } = await $Req({
        type: "GET",
        url: "/order/returnReview",
        data: {
          deliveryOrdersNo: expressNo,
          logisticsName: expressType,
          ordersNo: this.state.orderDetails.ordersNo,
          returnAddress: this.state.address,
          returnDes: this.state.selectorChecked,
          returnTime: new Date().getTime(),
          returnImg: this.state.uploadUrl.join(",")
        },
      });
      if (!data) return;
  
      Taro.showToast({
        title: "退货申请成功, 请等待审批!",
        icon: "none"
      })
  
      this.state.orderDetails.ordersState = "20007"
  
      this.setState({
        orderDetails: this.state.orderDetails
      })
    } else {
      Taro.showToast({
        title: "请填写物流信息",
        icon: "none"
      })
    }
  } 

  // 获取商家地址
  async getStoreAddress() {
    if (this.state.type == 1) {
      let { data } = await $Req({
        type: "GET",
        url: "/order/getSysOrderConf",
        data: {},
      });
      if (!data) return;

      this.setState({
        address: data.returnAddress
      })

    }
  }

  // 撤销退款退货申请
  async getCxSignIn(type, ordersNo) {
    
    let { data } = await $Req({
      type: "GET",
      url: "/order/revokeApply",
      data: {
        ordersNo,
        type
      },
    });
    if (!data) return;
    Taro.showToast({
      title: "撤销成功！"
    })

    setTimeout(function() {
      Taro.navigateBack(-1);
    }, 1000)
  }

  render() {
    return (
      <View className="page-order-refund">
        {
         this.state.orderDetails.ordersState  == "20005" ?
          <View>
            <View style="background: linear-gradient(270deg, #27B5F2 0%, #6DCDFF 100%); line-height: 110px; color: #fff; text-align:center; font-size: 20px;">请等待商家处理</View>
            <View style="padding: 10px; background-color: #fff;">
              <Text style="font-size: 14px; color #666;">您已成功发起退款申请，请耐心等候商家处理</Text>
              <View style="width: 70px; text-align:right; margin-top: 10px;">
                <AtButton type='primary' size='small'
                  onClick={
                    () => {
                      this.getCxSignIn(1, this.state.orderDetails.ordersNo);
                    }
                  }
                >撤销申请</AtButton>
              </View>
            </View>
          </View>
         :
          null
        }

        {
          this.state.orderDetails.ordersState  == "20006" ?
            <View>
              <View style="background: linear-gradient(270deg, #27B5F2 0%, #6DCDFF 100%); line-height: 110px; color: #fff; text-align:center; font-size: 20px;">商家处理完成</View>
              <View style="padding: 10px; background-color: #fff;">
                <Text style="font-size: 14px; color #666;">退款已完成</Text>
              </View>
            </View>
          :
            null
        }

        {
         this.state.orderDetails.ordersState  == "20007" ?
          <View>
            <View style="background: linear-gradient(270deg, #27B5F2 0%, #6DCDFF 100%); line-height: 110px; color: #fff; text-align:center; font-size: 20px;">请等待商家处理</View>
            <View style="padding: 10px; background-color: #fff;">
              <Text style="font-size: 14px; color #666;">您已成功发起退货申请，请耐心等候商家处理</Text>
              <View style="width: 70px; text-align:right; margin-top: 10px;">
                <AtButton type='primary' size='small'
                  onClick={
                    () => {
                      this.getCxSignIn(2, this.state.orderDetails.ordersNo);
                    }
                  }
                >撤销申请</AtButton>
              </View>
            </View>
          </View>
         :
          null
        }

        {
          this.state.orderDetails.ordersState  == "20008" ?
            <View>
              <View style="background: linear-gradient(270deg, #27B5F2 0%, #6DCDFF 100%); line-height: 110px; color: #fff; text-align:center; font-size: 20px;">商家处理完成</View>
              <View style="padding: 10px; background-color: #fff;">
                <Text style="font-size: 14px; color #666;">退货已完成</Text>
              </View>
            </View>
          :
            null
        }
        
        
        <View className="at-row">
          <View className="at-col">
            {this.state.orderDetails.orderDetailList.map((item) => {
              return (
                <View className="at-row shopping-show-box">
                  <View className="at-col show-box-c0">
                    <View className="at-row show-box-row">
                      <View className="at-col at-col-3 show-box-col-img">
                        <image className="img-goods" src={item.skuCoversUrl} />
                      </View>
                      <View className="at-col at-col-8 show-box-col-main">
                        <View className="at-row">
                          <View className="at-col">
                            <Text className="show-box-title">
                              {item.goodsName}
                            </Text>
                          </View>
                        </View>
                        <View className="at-row">
                          <View className="at-col">
                            <Text className="show-box-norms">
                              {item.skuTitleType}: {item.skuTitle}
                            </Text>
                          </View>
                        </View>
                      </View>
                      <View
                        className="at-col at-col-1"
                        style="padding-top: 20PX;text-align: right;font-size: 12PX;color: #999;"
                      >
                        <Text>x{item.quantity}</Text>
                      </View>
                    </View>
                  </View>
                </View>
              );
            })}

            <View style="background-color:#fff; font-size:14px; color: #666; line-height: 30px;">
              <View style="padding: 5px 15px;box-sizing: border-box;" className="at-row at-row__justify--between at-row__align--center">
                <View className="at-col at-col-6">
                  <Text>状态</Text>
                </View>
                <View className="at-col at-col-6" style="text-align:right;">
                  <Text>{this.state.orderDetails.ordersName}</Text>
                </View>
              </View>

              <View className='page-section'>
                <View className="at-row" style="width:100%">
                  <Picker mode='selector' range={this.state.selector} disabled={this.state.orderDetails.ordersState == "20007" || this.state.orderDetails.ordersState == "20005" || this.state.orderDetails.ordersState == "20006" || this.state.orderDetails.ordersState == "20008" ?  true: false} style="width:100%" onChange={this.onChange}>
                    <AtList>
                      <AtListItem
                        title={ (this.state.orderDetails.ordersState == "20002" || this.state.orderDetails.ordersState == "20007" ? "退货" : "退款") + "原因"}
                        extraText={this.state.selectorChecked}
                      />
                    </AtList>
                  </Picker>
                  <View style="line-height: 47px; border-bottom: 1px solid #eee;">
                    <AtIcon value="chevron-right" size="22" color="#ccc"></AtIcon>
                  </View>
                </View>
              </View>

              <View className="at-row at-row__align--center" style="padding: 5px 15px;">
                <View className="at-col">
                  <Text>{this.state.orderDetails.ordersState == "20002" || this.state.orderDetails.ordersState == "20007" ? "退货" : "退款"}金额:</Text>
                  <Text style="color:red;"> ￥ {this.state.orderDetails.refundAmount ? this.state.orderDetails.refundAmount : this.state.orderDetails.finalAmount}</Text>
                </View>
              </View>
              {
                this.state.orderDetails.useIntegral ? 
                  <View className="at-row at-row__align--center" style="padding: 5px 15px;">
                    <View className="at-col">
                      <Text>退还积分:</Text>
                      <Text>{this.state.orderDetails.useIntegral}</Text>
                    </View>
                  </View>
                :
                 null
              }
              {
                this.state.orderDetails.returnTime?
                  <View className="at-row at-row__align--center" style="padding: 5px 15px;">
                    <View className="at-col">
                      <Text>{this.state.orderDetails.ordersState == "20002" || this.state.orderDetails.ordersState == "20007" ? "退货" : "退款"}时间:</Text>
                      <Text> {this.state.orderDetails.returnTime }</Text>
                    </View>
                  </View>
                :
                null
              }
              {
                this.state.orderDetails.refundTime?
                  <View className="at-row at-row__align--center" style="padding: 5px 15px;">
                    <View className="at-col">
                      <Text>{this.state.orderDetails.ordersState == "20002" || this.state.orderDetails.ordersState == "20007" ? "退货" : "退款"}时间:</Text>
                      <Text> {this.state.orderDetails.refundTime }</Text>
                    </View>
                  </View>
                :
                null
              }
              
              
            </View>
            
            {
              (this.state.orderDetails.ordersState == "20005" || this.state.orderDetails.ordersState == "20006" )? 
                null
              :
              this.state.type == 2 ?
                <View style="padding: 30px; box-sizing:border-box; position:fixed; bottom: 50px; left: 50%; transform: translateX(-50%); width: 90%;" className="at-row at-row__justify--center at-row__align--center">
                  <View className="at-col">
                    <AtButton circle type="primary" className="btn-submit"
                      onClick={
                        () => {
                          this.callBackMoney()
                        }
                      }
                    >
                      退款
                    </AtButton>
                  </View>
                </View>
              :
              null
            }

            {
              this.state.orderDetails.ordersState == "20007" || this.state.orderDetails.ordersState == "20008" ? 
                null
              :
              this.state.type == 1 ? 
                <View style="padding: 0 15px 10px; box-sizing:border-box; background-color: #fff;">
                  <Text style="margin-bottom: 15px; font-size: 14px; color: #666;">退货地址：{this.state.address}</Text>
                  <View>
                    <AtInput
                      name="expressNo"
                      title='快递单号'
                      type='number'
                      placeholder='请输入快递单号（未收到包裹的填写0）'
                      value={this.state.expressNo}
                      onChange={(no) => {
                        this.setState({
                          expressNo: no 
                        })
                      }}
                    />
                    <AtInput
                      name="expressType"
                      title='物流公司'
                      type='text'
                      placeholder='请输入物流公司（未收到包裹的填写无）'
                      value={this.state.expressType}
                      onChange={(expressType) => {
                        this.setState({
                          expressType
                        })
                      }}
                    />
                  </View>
                  <View className="at-col" style="position:fixed; bottom: 50px; left: 50%; transform: translateX(-50%); width: 90%;">
                    <AtButton circle type="primary" className="btn-submit"
                      onClick={
                        () => {
                          this.callBackH()
                        }
                      }
                    >
                      退货
                    </AtButton>
                  </View>
                </View>
              :
                null
            }
          </View>
        </View>
        <View style="background-color:#fff; border-top:10px solid #eee; padding: 10px;">
          <View className="at-col" style="padding: 0 10px; font-size: 14px; color: #666;">
            <Text>上传凭证: {!this.state.files.length ? "无" : ''}</Text>
          </View>
          <AtImagePicker
            showAddBtn={this.state.orderDetails.ordersState == "20007" || this.state.orderDetails.ordersState == "20005" || this.state.orderDetails.ordersState == "20006" || this.state.orderDetails.ordersState == "20008" ? false: true}
            files={this.state.files}
            onChange={this.onChanges.bind(this)}
            onImageClick={this.onImageClick.bind(this)}
          />
        </View>
      </View>
    );
  }
}
